//
//  PeopleDataViewController.m
//  Cunli
//
//  Created by 湛亚 on 15/6/24.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "PeopleDataViewController.h"
#import "HeadImgTableViewCell.h"
//#import "SendMessageTableViewCell.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "UserInfoDetail.h"
#import "UIImageView+WebCache.h"
#import "ChatViewController.h"
#import "UIColor+Addition.h"

@interface PeopleDataViewController (){
    
    NSArray *dataArray;
    UserInfoDetail *userInfo;
    float screenWidth;
    float screenHeight;
    MBProgressHUD *moveHud;
    UIButton *sendMessageBtn,*managerBtn;
    BOOL isManager;
}

@property (strong, nonatomic) UIView *footerView;

@end

@implementation PeopleDataViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.title=@"详细资料";
    //self.view.backgroundColor=[UIColor convertHexColorToUIColor:0xcecece];
    isManager=[self isLiaisonMan];
    
    screenWidth=[UIScreen mainScreen].bounds.size.width;
    screenHeight=[UIScreen mainScreen].bounds.size.height;
    
    [self createNavBtn];
    [self getPeopleInfo];
}

-(void)createTableView{
    
    dataArray=[NSArray arrayWithObjects:@"地址:",@"职业:",@"手机:",@"个性签名:", nil];
    _peopleDataTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight) style:UITableViewStyleGrouped];
    _peopleDataTableView.dataSource=self;
    _peopleDataTableView.delegate=self;
    _peopleDataTableView.backgroundColor=[UIColor convertHexColorToUIColor:0xf6f6f6];
    if (userInfo.is_me==0&&userInfo.is_show==1&&userInfo.huanxin_username.length>0) {
        //不是本村人
        _peopleDataTableView.tableFooterView=self.footerView;
    }
    [self.view addSubview:_peopleDataTableView];
}

-(void)createNavBtn{
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 28, 28);
    [leftBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
}

-(void)goBack{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIView *)footerView
{
    if (_footerView == nil) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,screenWidth, 90)];
        _footerView.backgroundColor = [UIColor clearColor];
        
        sendMessageBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        sendMessageBtn.frame=CGRectMake(15, 10,screenWidth-30, 35);
        [sendMessageBtn addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
        sendMessageBtn.backgroundColor=[UIColor convertHexColorToUIColor:0xc93336];
        sendMessageBtn.layer.cornerRadius =3.0;
        [sendMessageBtn setTitle:@"发消息" forState:UIControlStateNormal];
        [_footerView addSubview:sendMessageBtn];
        
        if (isManager) {
            managerBtn=[UIButton buttonWithType:UIButtonTypeCustom];
            managerBtn.frame=CGRectMake(15, 55,screenWidth-30, 35);
            [managerBtn addTarget:self action:@selector(showAlertView) forControlEvents:UIControlEventTouchUpInside];
            managerBtn.backgroundColor=[UIColor convertHexColorToUIColor:0x999999];
            managerBtn.layer.cornerRadius=3.0;
            NSString *btnTitle=[userInfo.is_banned isEqualToString:@"0"]?@"屏蔽该村民的发言":@"解除该村民的发言屏蔽";
            [managerBtn setTitle:btnTitle forState:UIControlStateNormal];
            [_footerView addSubview:managerBtn];
        }
    }
    return _footerView;
}

-(void)getPeopleInfo{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:self.touserid forKey:@"touserid"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"getinfo_addressbook.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        
        if ([[result objectForKey:@"response"] isEqualToString:@"getinfo_member"]) {
            
            NSDictionary *userInfoDic=[result objectForKey:@"userinfo"];
            //userInfo=[[UserInfoDetail alloc]initWithDictionary:userInfoDic];
            userInfo=[UserInfoDetail yy_modelWithDictionary:userInfoDic];
            [self createTableView];
        }else{
            
            [Config showHUDWithText:@"获取信息失败!" andImage:@"error"];
        }
    
    }failureAction:^{
        
        [Config showHUDWithText:@"获取信息失败!" andImage:@"error"];
    }];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 25;
    }
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section==0) {
        return 1;
    }else{
        if ([userInfo.is_use isEqualToString:@"1"]) {
            return 4;
        }else{
            return 5;
        }
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier=@"cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    switch (indexPath.section) {
        case 0:{
            
            UIImageView *headImgView=[[UIImageView alloc]initWithFrame:CGRectMake(15, 10, 50, 50)];
            [headImgView setImageWithURL:[NSURL URLWithString:userInfo.pic] placeholderImage:[UIImage imageNamed:@"default_touxiang.png"]];
            headImgView.layer.cornerRadius = 25;
            headImgView.clipsToBounds = YES;
            [cell addSubview:headImgView];
            
            CGFloat width=[self getNameLabelWidth]>screenWidth-100?screenWidth-100:[self getNameLabelWidth];
            UILabel *nameLabel=[[UILabel alloc]initWithFrame:CGRectMake(75,10,width, 24)];
            nameLabel.text=userInfo.truename;
            nameLabel.font=[UIFont systemFontOfSize:16];
            [cell addSubview:nameLabel];
            
            UIImageView *sexImgView=[[UIImageView alloc]initWithFrame:CGRectMake(nameLabel.frame.origin.x+nameLabel.frame.size.width+4, 14, 14, 14)];
            if ([userInfo.sex isEqualToString:@"男"]) {
                sexImgView.image=[UIImage imageNamed:@"manimg"];
            }else if ([userInfo.sex isEqualToString:@"女"]){
                sexImgView.image=[UIImage imageNamed:@"womanimg"];
            }
            [cell addSubview:sexImgView];
            
            UILabel *roleLabel=[[UILabel alloc]initWithFrame:CGRectMake(75, 36, 50, 24)];
            roleLabel.text=userInfo.rolename;
            roleLabel.font=[UIFont systemFontOfSize:16];
            roleLabel.textColor=[UIColor convertHexColorToUIColor:0x999999];
            [cell addSubview:roleLabel];
            
            return cell;
        }
            break;
            
        case 1:{
            
            cell.detailTextLabel.textAlignment=0;
            cell.detailTextLabel.numberOfLines=0;
            cell.textLabel.font=[UIFont systemFontOfSize:15];
            cell.detailTextLabel.font=[UIFont systemFontOfSize:15];
            if (indexPath.row==0) {
                cell.textLabel.text=@"地址";
                cell.detailTextLabel.text=userInfo.area;
            }else if (indexPath.row==1){
                cell.textLabel.text=@"职业";
                cell.detailTextLabel.text=userInfo.career;
            }else if (indexPath.row==2){
                
                for (int i = 0; i<[userInfo.mobile length]; i++) {
                    //截取字符串中的每一个字符
                    if (i>2&&i<7) {
                        NSRange range = NSMakeRange(i, 1);
                        userInfo.mobile=[userInfo.mobile stringByReplacingCharactersInRange:range withString:@"*"];
                    }
                }
                cell.textLabel.text=@"联系方式";
                cell.detailTextLabel.text=userInfo.mobile;
            }else if(indexPath.row==3){
                cell.detailTextLabel.numberOfLines=0;
                cell.textLabel.text=@"个性签名";
                cell.detailTextLabel.text=userInfo.signaure;
 
            }else{
                
                cell.textLabel.text=@"此村民暂未使用";
                cell.textLabel.textColor=[UIColor convertHexColorToUIColor:0x5fbafd];
            }
            
            return cell;
        }
            break;
        default:
            return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0) {
        return 70;
    }
    if (indexPath.row==3) {
        return [self heightWithString:userInfo.signaure];
    }
    return 40;
}

-(void)sendMessage{
    
    ChatViewController *chatVC=[[ChatViewController alloc]initWithChatter:userInfo.huanxin_username isGroup:NO];
    chatVC.title=userInfo.truename;
    chatVC.extDic=@{ @"nicheng" : userInfo.truename, @"pic" : userInfo.pic};
    [self.navigationController pushViewController:chatVC animated:YES];
}

-(float)heightWithString:(NSString *)introduce{
    
    CGRect rect = [introduce boundingRectWithSize:CGSizeMake(screenWidth-30, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15.0f]} context:nil];
    CGFloat height = ceilf(rect.size.height);
    return height + 20;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 判断是否是联络员

-(BOOL)isLiaisonMan{
    
    NSDictionary *user=[[NSUserDefaults standardUserDefaults]objectForKey:@"userinfo"];
    NSString *userRoleString=[user objectForKey:@"groupid"];
    if ([userRoleString isEqualToString:@"9"]) {
        return YES;
    }else{
        return NO;
    }
}

#pragma mark -联络员屏蔽与解除屏蔽

-(void)showAlertView{
    
    NSString *showMessage=[userInfo.is_banned isEqualToString:@"0"]?@"确定屏蔽该村民的发言?":@"确定解除该村民的发言屏蔽?";
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:showMessage delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag=1001;
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex==1) {
        
        if (alertView.tag==1001) {
            [self managerCurrentUser];
        }
    }
}

-(void)managerCurrentUser{
    
    NSString *type=[userInfo.is_banned isEqualToString:@"0"]?@"1":@"2";
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:type forKey:@"type"];
    [CheckParams setObject:self.touserid forKey:@"to_userid"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"banned_member.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        
        if ([[result objectForKey:@"response"] isEqualToString:@"banned_member"]) {
            
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = @"操作成功!";
            [hud hide:YES afterDelay:1];
            userInfo.is_banned=[userInfo.is_banned isEqualToString:@"0"]?@"1":@"0";
            [managerBtn setTitle:[userInfo.is_banned isEqualToString:@"0"]?@"屏蔽该村民的发言":@"解除该村民的发言屏蔽" forState:UIControlStateNormal];
            
        }else{
            
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
            hud.labelText = @"操作失败!";
            [hud hide:YES afterDelay:1];
        }
        
    }failureAction:^{
        
    }];
    
}

- (CGFloat)getNameLabelWidth{
    
    CGSize resultSize = CGSizeZero;
    if (userInfo.truename.length <= 0) {
        return resultSize.width;
    }
    resultSize = [userInfo.truename boundingRectWithSize:CGSizeMake(screenWidth-100, 24) options:(NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin)  attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16.0f]}  context:nil].size;
    resultSize = CGSizeMake(MIN(screenWidth, ceilf(resultSize.width)), MIN(24, ceilf(resultSize.height)));
    return resultSize.width;
}

@end
